﻿
var OneApp = new OneAppFactory();


function OneAppFactory() { };

OneAppFactory.prototype.PROPERTYCHANGEEVENT = "PropertyChange";

OneAppFactory.prototype.RegisterProperty = function (instance, propertyName) {
    var initialValue = instance[propertyName];
    Object.defineProperty(instance, propertyName, {
        get: function () {
            if (!instance.base.propertyStore[propertyName]) {
                instance.base.propertyStore[propertyName] = null;
            }
            return instance.base.propertyStore[propertyName];
        },
        set: function (value) {
            if (instance.base.propertyStore[propertyName] != value) {
                instance.base.propertyStore[propertyName] = value;
                instance.base.RaisePropertyChanged(propertyName);
                instance.base.OnPropertyChanged(propertyName);
            }
        }
    });

    instance.base.propertyStore[propertyName] = initialValue;
};

OneAppFactory.prototype.RegisterViewModel = function (viewmodel) {
    var names = Object.keys(viewmodel);
    viewmodel.base = new ViewModelBase();
    var that = this;
    names.forEach(function (key) {
        that.RegisterProperty(viewmodel, key);
    });
};

function DelegateCommand(executeCallBack, canExecuteCallBack) {
    this.executeCallBack = executeCallBack;
    this.canExecuteCallBack = canExecuteCallBack;
}

DelegateCommand.prototype.execute = function(parameter) {
    this.executeCallBack(parameter);
}

DelegateCommand.prototype.canExecute = function (parameter) {
    return this.canExecuteCallBack(parameter);
}

function ViewModelBase() {
    this.propertyStore = {};
};

// virtual function
ViewModelBase.prototype.OnPropertyChanged = function (propertyName) {};

ViewModelBase.prototype.RaisePropertyChanged = function (propertyName) {
    $(this).trigger({ type: OneApp.PROPERTYCHANGEEVENT, propertyName: propertyName });
};